
package com.gcloud.mesh.dcs.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.constant.enums.SysLogOperateType;
import org.jeecg.common.constant.enums.SysLogType;
import org.jeecg.common.exception.MyBusinessException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gcloud.framework.db.PageResult;
import com.gcloud.mesh.dcs.annotation.ParamSecurity;
import com.gcloud.mesh.dcs.entity.AppEntity;
import com.gcloud.mesh.dcs.service.AppService;
import com.gcloud.mesh.header.msg.BaseReplyMsg;
import com.gcloud.mesh.header.msg.dcs.CreateAppMsg;
import com.gcloud.mesh.header.msg.dcs.DeleteAppMsg;
import com.gcloud.mesh.header.msg.dcs.MyUpdateAppSchedulerConfigMsg;
import com.gcloud.mesh.header.msg.dcs.PageAppMsg;
import com.gcloud.mesh.header.msg.dcs.PageInstanceMsg;
import com.gcloud.mesh.header.msg.dcs.PageVmMsg;
import com.gcloud.mesh.header.msg.dcs.SyncAppMsg;
import com.gcloud.mesh.header.msg.dcs.UpdateAppMsg;
import com.gcloud.mesh.header.vo.dcs.AppDetailItemVo;
import com.gcloud.mesh.header.vo.dcs.AppInstanceType;
import com.gcloud.mesh.header.vo.dcs.AppInstanceVo;
import com.gcloud.mesh.header.vo.dcs.AppItemVo;
import com.gcloud.mesh.header.vo.dcs.VmItemVo;

import cn.hutool.core.lang.UUID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "应用管理")
@RestController
@RequestMapping("/app")
@Slf4j
public class AppController {

	@Autowired
	private AppService service;

	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Autowired
	private AppService appService;

	// 处理Mass Assignment: Insecure Binder Configuration
	@InitBinder
	public void populateCustomerRequest(WebDataBinder binder) {
		binder.setDisallowedFields(new String[] {});
	}

	// @AutoLog(value = "新增应用", operateType = CommonConstant.OPERATE_TYPE_ADD)
	@ApiOperation(value = "新增应用", notes = "新增应用")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@RequiresPermissions(value = { "appCreate" })
	@ParamSecurity(enabled = true)
	public void create(@Valid CreateAppMsg msg) throws Exception {
		String id = service.create(msg);
		StringBuffer buff = new StringBuffer();
		buff.append("新增应用；ID:" + id);
		buff.append("，" + "应用名称：" + msg.getName());
		sysBaseAPI.addLog(buff.toString(), SysLogType.OPERATE, SysLogOperateType.ADD, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源");
		// sysBaseAPI.addLog("新增应用；ID:" + id, null,
		// CommonConstant.OPERATE_TYPE_ADD);
	}

	// @AutoLog(value = "删除应用", operateType =
	// CommonConstant.OPERATE_TYPE_DELETE)
	@ApiOperation(value = "删除应用", notes = "删除应用")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@RequiresPermissions(value = { "appDelete" })
	@ParamSecurity(enabled = true)
	public void delete(@Valid DeleteAppMsg msg) throws Exception {
		AppEntity app = service.delete(msg);
		sysBaseAPI.addLog("删除应用；ID:" + msg.getAppId() + "，应用名称：" + app.getName(), SysLogType.OPERATE, SysLogOperateType.DELETE, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源");
	}

	// @AutoLog(value = "更新应用", operateType =
	// CommonConstant.OPERATE_TYPE_UPDATE)
	@ApiOperation(value = "更新应用", notes = "更新应用")
	@RequestMapping(value = "/update1", method = RequestMethod.POST)
	@RequiresPermissions(value = { "appUpdate" })
	@ParamSecurity(enabled = true)
	public void update(@Valid UpdateAppMsg msg) throws Exception {
		service.update(msg);
		StringBuffer buff = new StringBuffer();
		buff.append("更新应用；ID:" + msg.getAppId());
		buff.append("，" + "应用名称：" + msg.getName());

		sysBaseAPI.addLog(buff.toString(), SysLogType.OPERATE, SysLogOperateType.UPDATE, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源");

		LoginUser loginUser = getLoginUser();
		if (loginUser != null) {
			String sql = String.format("update `dcs_apps` set `cloud_resource_id`=%s,`create_time`=%s,`name`=%s,`type`=%s where `id`=%s", msg.getAppId(), DateUtils.formatDate(), msg.getName(), 1, java.util.UUID.randomUUID());
			sysBaseAPI.addLog(String.format("%s", sql), SysLogType.DEBUG, SysLogOperateType.DB_DEBUG, loginUser.getId());
		}
	}

	// @AutoLog(value = "更新应用调度配置", operateType =
	// CommonConstant.OPERATE_TYPE_CONFIG)
	@ApiOperation(value = "更新应用调度配置", notes = "更新应用调度配置")
	@RequestMapping(value = "/update_scheduler_config", method = RequestMethod.POST)
	@RequiresPermissions(value = { "appUpdate_scheduler_config" })
	@ParamSecurity(enabled = true)
	public void updateSchedulerConfig(@Valid @RequestBody MyUpdateAppSchedulerConfigMsg msg) throws Exception {
		String id = service.myUpdateSchedulerConfig(msg);
		sysBaseAPI.addLog("设置调度触发策略，数据中心ID："+id, SysLogType.OPERATE, SysLogOperateType.UPDATE, null, null, "多数据中心调度-动态调度机制-调度触发策略设置");
		// sysBaseAPI.addLog("更新应用调度配置；应用调度配置ID:" + id,
		// CommonConstant.LOG_TYPE_OPERATE, CommonConstant.OPERATE_TYPE_CONFIG);
	}

	// @AutoLog(value = "查询应用列表", operateType =
	// CommonConstant.OPERATE_TYPE_LIST, module =
	// "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源")
	@ApiOperation(value = "应用分页列表", notes = "应用分页列表", response = PageResult.class)
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	@RequiresPermissions(value = { "appPage" })
	@ParamSecurity(enabled = true)
	public PageResult<AppItemVo> page(@Valid PageAppMsg msg) throws Exception {
		if ("应用资源详情".equals(msg.getContent())) {
			sysBaseAPI.addLog("查看应用资源详情；ID:" + UUID.randomUUID().toString(), SysLogType.OPERATE, SysLogOperateType.DETAIL, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源");
		} else {
			sysBaseAPI.addLog(msg.getContent() != null ? msg.getContent() : "查询应用资源列表", SysLogType.OPERATE, SysLogOperateType.QUERY, null, null, msg.getTitle() != null ? msg.getTitle() : "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源");
		}

		return service.page(msg);
	}

	// @AutoLog(value = "应用同步", operateType = CommonConstant.OPERATE_TYPE_SYNC, module = "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源")
	@ApiOperation(value = "应用同步", notes = "应用同步")
	@RequestMapping(value = "/sync", method = RequestMethod.POST)
	@ParamSecurity(enabled = true)
	public BaseReplyMsg sync(@Valid @RequestBody SyncAppMsg syncAppMsg) throws Exception {
		BaseReplyMsg reply = new BaseReplyMsg();
		String res = service.syncGceApp(syncAppMsg);
		sysBaseAPI.addLog("应用资源同步"+"("+res+")", SysLogType.OPERATE, SysLogOperateType.SYNC, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源");
		reply.setData(res);
		return reply;
	}

	@ApiOperation(value = "获取集群namespace", notes = "获取集群namespace")
	@RequestMapping(value = "/queryNamespaceList", method = RequestMethod.GET)
	@ParamSecurity(enabled = true)
	public BaseReplyMsg queryNamespacesList(String cloudResourceId, String appId) throws Exception {
		// if(StringUtils.isBlank(datacenterId)) throw new MyBusinessException("datacenterId不能为空");
		if(StringUtils.isBlank(cloudResourceId)) throw new MyBusinessException("cloudResourceId不能为空");
		List<AppInstanceType> list = appService.queryAppList(cloudResourceId, appId);
		BaseReplyMsg reply = new BaseReplyMsg();
		reply.setData(list);
		return reply;
	}
	
	@ApiOperation(value = "应用详情", notes = "获取集群应用详情")
	@RequestMapping(value = "/detail")
	@ParamSecurity(enabled = true)
	public BaseReplyMsg detail(String appId) throws Exception {
		// if(StringUtils.isBlank(datacenterId)) throw new MyBusinessException("datacenterId不能为空");
		if(StringUtils.isBlank(appId)) throw new MyBusinessException("appId不能为空");
		AppDetailItemVo detail = appService.detail(appId);
		BaseReplyMsg reply = new BaseReplyMsg();
		reply.setData(detail);
		return reply;
	}


	private LoginUser getLoginUser() {
		LoginUser sysUser = null;
		try {
			sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
		} catch (Exception e) {
			sysUser = null;
		}
		return sysUser;
	}
	
	@ApiOperation(value = "虚拟机列表", notes = "虚拟机列表", response = PageResult.class)
	@RequestMapping(value = "/vmPage", method = RequestMethod.POST)
	public PageResult<VmItemVo> vmpage(@Valid PageVmMsg msg) throws Exception {
		return service.vmpage(msg);
	}
	
	
	@ApiOperation(value = "迁移实例列表", notes = "迁移实例列表", response = PageResult.class)
	@RequestMapping(value = "/instancePage", method = RequestMethod.POST)
	public PageResult<AppInstanceVo> instancePage(@Valid PageInstanceMsg msg) throws Exception {
		return service.instancePage(msg);
	}
	
	
}
